import 'swiper/css'

import { Swiper, SwiperSlide } from 'swiper/react'
import { Tooltip } from 'antd';
import { useState } from 'react';
import { VChartA01, VChartA02 } from '../../Utils/ChartsRender'
import { useRequest } from 'alova/client';
import { Http } from '../../Utils/Api';
import { useEventEmitter, useMount } from 'ahooks';
import { useNavigate } from 'react-router-dom'

import { startTitleStore } from '../../Config/zustand'
import { SwapOutlined } from '@ant-design/icons';
import { useEffect } from 'react';


import { TopDateTemplate } from '../data'

const List = [
    { label: '新签订单目标', value: 'A01' },
    { label: '新签订单完成', value: 'A02' },
    { label: '完成比例', value: 'A03' },
    { label: '结转订单', value: 'A04' },
    { label: '在手订单', value: 'A05' },
]

const TypeTopNav = [
    { value: 0, label: '新签合同订单完成情况统计' },
    { value: 1, label: '新签合同订单' },
]

const ListTableTop = [
    { label: '单位名称', width: 200 },
    { label: '新签\n订单目标', flex: 122 },
    { label: '完成值', flex: 366, child: [{ label: '本月完成', flex: 1 }, { label: '本年\n累计完成', flex: 1 }, { label: '完成比', flex: 1 }] },
    { label: '省内', flex: 244, child: [{ label: '本月完成', flex: 1 }, { label: '本年\n累计完成', flex: 1 }] },
    { label: '省外', flex: 244, child: [{ label: '本月完成', flex: 1 }, { label: '本年\n累计完成', flex: 1 }] },
    { label: '国际', flex: 244, child: [{ label: '本月完成', flex: 1 }, { label: '本年\n累计完成', flex: 1 }] },
    { label: '百分比', width: 270 },
]

const PinMapping = [
    { value: '省内占比', label: '省内', color: '#4B77A0' },
    { value: '省外占比', label: '省外', color: '#BC7222' },
    { value: '国外占比', label: '国际', color: '#5FB8A2' },
]

const TopNavMapping = [
    '建工项目', '龙建股份', '安装集团', '水利水电集团', '水投项目', '一恒建设', '龙创置业', '一森生态',
    '建工项目1', '龙建股份1', '安装集团1', '水利水电集团1', '水投项目1', '一恒建设1', '龙创置业1', '一森生态1',
]

const getChartData2 = (num) => {
    let countries = "北京市,天津市,河北省,山西省,内蒙古自治区,辽宁省,吉林省,黑龙江省,上海市,江苏省,浙江省,安徽省,福建省,江西省,山东省,河南省,湖北省,湖南省,广东省,广西壮族自治区,海南省,重庆市,四川省,贵州省,云南省,西藏自治区,陕西省,甘肃省,青海省,宁夏回族自治区,新疆维吾尔自治区,香港特别行政区,澳门特别行政区,台湾省".split(",")
    const data = [...Array(num)].map((_, i) => ({ uuid: i, type: countries[i % countries.length], value: Math.floor(Math.random() * 100) }))
    return data
}

const UnitMapping = { 1: '亿元', 2: '万元' }

const A02 = ({ uuid }) => {
    const navigate = useNavigate()
    const { updateProjectTitle } = startTitleStore()

    const [Date, setDate] = useState()

    const [DataWA01, setDataWA01] = useState({ A01: 0, A02: 0, A03: 0, A04: 0, A05: 0 })
    const [DataYA01, setDataYA01] = useState({ A01: 0, A02: 0, A03: 0, A04: 0, A05: 0 })
    const [DataYFA01, setDataYFA01] = useState({ A01: 0, A02: 0, A03: 0, A04: 0, A05: 0 })
    const [UnitSwitch, setUnitSwitch] = useState(1)

    const [Active, setActive] = useState(0)
    const [ListData, setListData] = useState([])
    const [ChartsFieldBar, setChartsFieldBar] = useState()
    const [ChartsStyleBar, setChartsStyleBar] = useState()
    const [ChartsFieldPie, setChartsFieldPie] = useState()
    const [ChartsStylePie, setChartsStylePie] = useState()

    const [TopNavList, setTopNavList] = useState([])
    const [NavActive, setNavActive] = useState()


    const [ChartDataA02, setChartDataA02] = useState(getChartData2(34))

    const { send } = useRequest(({ url, params }) => Http({ url, params }), { immediate: false })

    useEffect(() => {
        if (NavActive) {
            send({ url: 'getScreenOperateProvinceList', params: { OrganizationUuid: NavActive } }).then(res => {
                setChartDataA02(res.data.list.map(({ uuid, province, yearAmount }) => ({ uuid: uuid, type: province, value: yearAmount })))
            })
        }
    }, [NavActive])


    const onDownward = (e, levelId) => {
        if (levelId > 0) navigate(`/Start/Page/A02/${e}`)
    }

    useEffect(() => {
        const YearMonth = sessionStorage.getItem('YearMonth')
        if (YearMonth) setDate(YearMonth)
        else send({ url: 'getScreenManageYearMonth', params: { organizationUuid: uuid } }).then(res => setDate(res.data.eventDate))
    }, [uuid])

    useEffect(() => {
        if (Date) {
            send({ url: 'getJSONData', params: { Uuid: 'ChartStyle/经营柱图' } }).then(res => {
                setChartsFieldBar(res.ChartsField)
                setChartsStyleBar(res.ChartsStyle)
            })
            send({ url: 'getJSONData', params: { Uuid: 'ChartStyle/经营饼图' } }).then(res => {
                setChartsFieldPie(res.ChartsField)
                setChartsStylePie(res.ChartsStyle)
            })

            send({ url: 'getScreenManageList', params: { organizationUuid: uuid, YearMonth: Date } }).then(res => {
                const { organizationName, wanyuan, yiyuanzhengshu, yiyuanxiaoshu } = res.data
                updateProjectTitle(organizationName)
                setDataWA01({ A01: wanyuan.新签订单目标, A02: wanyuan.新签订单完成, A03: wanyuan.经营完成比例, A04: wanyuan.经营结转订单, A05: wanyuan.经营在手订单 })
                setDataYA01({ A01: yiyuanzhengshu.新签订单目标, A02: yiyuanzhengshu.新签订单完成, A03: yiyuanzhengshu.经营完成比例, A04: yiyuanzhengshu.经营结转订单, A05: yiyuanzhengshu.经营在手订单 })
                setDataYFA01({ A01: yiyuanxiaoshu.新签订单目标, A02: yiyuanxiaoshu.新签订单完成, A03: yiyuanxiaoshu.经营完成比例, A04: yiyuanxiaoshu.经营结转订单, A05: yiyuanxiaoshu.经营在手订单 })
            })
            send({ url: 'getScreenOperateCompanyList', params: { organizationUuid: uuid, YearMonth: Date } }).then(res => setListData(res.data.list))
            send({ url: 'getScreenOperateProvinceCompanyList' }).then(res => {
                setTopNavList(res.data.list)
                setNavActive(res.data.list[0].uuid)
            })
        }
    }, [Date, uuid])


    const Event = useEventEmitter()
    Event.useSubscription(val => {
        const { type, data } = val
        if (type === 'onDate') setDate(data)
        if (type === 'onUnit') setUnitSwitch(data === 1 ? 2 : 1)
    })


    return (
        <div className='A02'>
            {Date && <TopDateTemplate date={Date} unit={UnitSwitch} Event={Event} />}
            <div className="DataA01">
                {List.map(({ label, value }, index) =>
                    <div key={index}>
                        <div >{label}</div>
                        <Tooltip placement='bottom' title={UnitSwitch === 1 ? DataYFA01[value] : DataWA01[value]} overlayStyle={{ fontSize: 48, fontFamily: 'R-Spectr' }}>
                            <div>{UnitSwitch === 1 ? DataYA01[value] : DataWA01[value]}</div>
                        </Tooltip>
                    </div>
                )}
            </div>
            <div className='TypeBox'>
                <div className="Title">
                    {TypeTopNav.map(({ value, label }) =>
                        <div key={value} className={Active === value ? 'active' : ''} style={{ '--deg': Active === 0 ? '90deg' : '270deg' }} onClick={() => setActive(value)}>{label}</div>
                    )}
                </div>
                {Active === 0 ?
                    <div className='List'>
                        <div className='Top'>
                            {ListTableTop.map(({ label, width, flex, child }, index) => {
                                if (child) {
                                    return (
                                        <div key={index} style={{ flex }} className='Top__A02'>
                                            <div>{label}</div>
                                            <div>{child.map(({ label }, index) => <div key={index} >{label}</div>)}</div>
                                        </div>
                                    )
                                } else { return (<div key={index} style={flex ? { flex } : { width }} className='Top__A01'>{label}</div>) }
                            })}
                        </div>
                        <div className='List_Item'>
                            {ListData.map(({
                                uuid, levelId, 公司名称, 新签订单目标, 本月完成, 本年累计完成, 完成比,
                                省内本月完成, 省内本年累计完成, 省外本月完成, 省外本年累计完成, 国外本月完成, 国外本年累计完成,
                                ...item
                            }) => {
                                const ChartDataA01 = [
                                    { name: '省内', type: '省内', value: item.省内占比 },
                                    { name: '省外', type: '省外', value: item.省外占比 },
                                    { name: '国际', type: '国际', value: item.国外占比 }
                                ]
                                return (
                                    <div key={uuid}>
                                        <div onClick={() => onDownward(uuid, levelId)}>{公司名称}</div>
                                        <div>
                                            <div>{新签订单目标}</div>
                                            <div>{本月完成}</div>
                                            <div>{本年累计完成}</div>
                                            <div>{完成比}</div>
                                            <div>{省内本月完成}</div>
                                            <div>{省内本年累计完成}</div>
                                            <div>{省外本月完成}</div>
                                            <div>{省外本年累计完成}</div>
                                            <div>{国外本月完成}</div>
                                            <div>{国外本年累计完成}</div>
                                        </div>
                                        <div>
                                            <div>
                                                {ChartsFieldPie && ChartsStylePie && <VChartA02 data={ChartDataA01} field={ChartsFieldPie} style={ChartsStylePie} />}
                                            </div>
                                            <div>
                                                {PinMapping.map(({ value, label, color }, index) =>
                                                    <div key={index} style={{ '--color': color }}>
                                                        <div>{label}</div>
                                                        <div>{item[value]}%</div>
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                )
                            })}
                        </div>
                    </div> :
                    <div className='Charts'>
                        <div className='Charts__Nav'>
                            <Swiper
                                className="SwiperBox"
                                loop={false}
                                autoplay={false}
                                slidesPerView={9}
                                spaceBetween={0}
                            >
                                {TopNavList.map(({ uuid, 公司名称 }) =>
                                    <SwiperSlide key={uuid} onClick={() => setNavActive(uuid)}>
                                        <div className={`swiperItem${NavActive === uuid ? ' active' : ''}`}>{公司名称}</div>
                                    </SwiperSlide>
                                )}
                            </Swiper>
                        </div>
                        <div className='Charts__Box'>
                            <div className='left'>
                                <div className='Title'>
                                    <div>按地区新签合同订单完成情况统计</div>
                                    <div />
                                </div>
                                <div className='Charts__details'>
                                    {ChartsFieldBar && ChartsStyleBar && <VChartA01 data={ChartDataA02} field={ChartsFieldBar} style={ChartsStyleBar} />}
                                </div>
                            </div>
                            <div className='right'>
                                <div>
                                    <div>
                                        <div>{TopNavList.find(v => v.uuid === NavActive)?.公司名称 || ''}</div>
                                        <div>新签订单总完成（万元）</div>
                                    </div>
                                    <div> {TopNavList.find(v => v.uuid === NavActive)?.本年累计完成 || 0} </div>
                                </div>
                            </div>
                        </div>
                    </div>
                }
            </div>
        </div >
    );
};

export default A02;